package com.gm.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.gm.springboot.bean.UserInfo;
import com.gm.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @Author Administrator
 * @Date 2020/7/2 13:48
 **/
@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @ResponseBody
    @PostMapping("/user/login")
    public String doLogin(@RequestParam("username")String username,
                          @RequestParam("password")String password,
                          HttpSession session,
                          Model model){
        System.out.println("aaaaaaaaaaaaaaaaaaaaaa");
        JSONObject jsonObject=new JSONObject();
        UserInfo user=this.userService.findUserByName(username);
        if (user!=null){
            if(user.getPassword().equals(password)){
                System.out.println("登陆成功");
                session.setAttribute("user",user);
                jsonObject.put("result","0");
            }else{
                System.out.println("密码错误");
                model.addAttribute("msg","密码错误");
                jsonObject.put("result","1");
            }

        }else {
            System.out.println("账号不存在");
            model.addAttribute("msg","您输入的账号不存在");
            jsonObject.put("result","2");
        }
        return jsonObject.toString();

    }
    @ResponseBody
    @PostMapping("/addUser")
    public String addUser(UserInfo userInfo){
        System.out.println(userInfo);
        System.out.println("bbbbbbbbbbbbbbbb");
        JSONObject jsonObject=new JSONObject();
        UserInfo user=this.userService.findUserByName(userInfo.getUsername());
        if (user==null){
            Date date=new Date();
            userInfo.setCreateTime(date);
            userInfo.setUpdateTime(date);
            this.userService.addUser(userInfo);
            jsonObject.put("result","0");
        }else {
            jsonObject.put("result","1");
        }
        return jsonObject.toString();


    }
}
